package com.study.system;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 服务器的IO处理
 */
public class DanmuServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //客户端的通道组
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //客户端上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //把客户端加到通道组里
        channels.add(ctx.channel());
        //群发消息
        channels.writeAndFlush(ctx.channel().remoteAddress() + "上线了");
    }

    //客户端下线
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channels.writeAndFlush(ctx.channel().remoteAddress() + "下线了");
    }

    //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame s) throws Exception {
        System.out.println("服务器收到数据：" + s.text());
        //给客户端发送消息
        channels.writeAndFlush(new TextWebSocketFrame(s.text()));
    }
}